package com.zzt.appframe8;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.core.content.ContextCompat;


/**
 * @author: zeting
 * @date: 2020/11/9
 * 带有删除图标的输入框
 */
public class DeleteIconEditText extends AppCompatEditText {
    private Drawable ic_delete; // 删除图标
    private Drawable ic_delete_error;
    private int delete_x, delete_y, delete_width, delete_height; // 删除图标起点(x,y)、删除图标宽、高（px）

    private DeleteEditTextFocusListener deleteFocusListener;
    private DeleteEditTextChangedListener deleteChangedListener;
    // 下划线颜色
    private int underscoreCheckColor;
    private int underscoreUnCheckColor;

    private View lineView;

    private boolean error = false;

    /**
     * 设置下划线
     *
     * @param lineView
     * @param underscoreCheckColor
     * @param underscoreUnCheckColor
     */
    public void setUnderscoreCheckColor(View lineView, int underscoreCheckColor, int underscoreUnCheckColor) {
        this.lineView = lineView;
        this.underscoreUnCheckColor = underscoreUnCheckColor;
        this.underscoreCheckColor = underscoreCheckColor;
    }

    public void addDeleteFocusListener(DeleteEditTextFocusListener deleteFocusListener) {
        this.deleteFocusListener = deleteFocusListener;
    }

    public void addDeleteChangedListener(DeleteEditTextChangedListener listener) {
        this.deleteChangedListener = listener;
    }

    public DeleteIconEditText(Context context) {
        super(context);
        init(context);
    }

    public DeleteIconEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public DeleteIconEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    /**
     * 步骤1：初始化属性
     */
    private void init(Context context) {
        // 2. 根据资源ID获取图标资源（转化成Drawable对象）
        ic_delete = ContextCompat.getDrawable(context, R.mipmap.icon_login_edit_delete);
        // 3. 设置图标大小
        // 起点(x，y)、宽= left_width、高 = left_height
        delete_x = 0;
        delete_y = 0;
        delete_width = getResources().getDimensionPixelOffset(R.dimen.margin_21dp);
        delete_height = getResources().getDimensionPixelOffset(R.dimen.margin_21dp);
        ic_delete.setBounds(delete_x, delete_y, delete_width, delete_height);

        // 消除自带下划线
        setBackground(null);
    }

    /**
     * 复写EditText本身的方法：onTextChanged（）
     * 调用时刻：当输入框内容变化时
     */
    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
        setDeleteIconVisible(hasFocus() && text.length() > 0, hasFocus());
        if (deleteChangedListener != null) {
            deleteChangedListener.onTextChanged(text);
        }
    }

    /**
     * 复写EditText本身的方法：onFocusChanged（）
     * 调用时刻：焦点发生变化时
     */
    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        setDeleteIconVisible(focused && length() > 0, hasFocus());
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                Drawable drawable = ic_delete;
                if (drawable != null && event.getX() <= (getWidth() - getPaddingRight())
                        && event.getX() >= (getWidth() - getPaddingRight() - drawable.getBounds().width())) {
                    setText("");
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    /**
     * 设置删除图标
     */
    private void setDeleteIconVisible(boolean deleteVisible, boolean focused) {
        setCompoundDrawables(null, null, deleteVisible ? ic_delete : null, null);
        if (deleteFocusListener != null) {
            deleteFocusListener.onFocusChanged(focused);
        }
        // 设置下划线颜色
        if (lineView != null) {
            Log.d( "TAG", "下划线颜色  ：  " + focused + " -" + getHint().toString());
            if (error) {
                lineView.setBackgroundColor(ContextCompat.getColor(lineView.getContext(), R.color.color_FF4164));
            } else if (focused) {
                lineView.setBackgroundColor(ContextCompat.getColor(lineView.getContext(), underscoreCheckColor));
            } else {
                lineView.setBackgroundColor(ContextCompat.getColor(lineView.getContext(), underscoreUnCheckColor));
            }
        }
        invalidate();
    }

    /**
     * 设置错误信息
     *
     * @param b
     */
    public void setErrorInfo(boolean b) {
        if (b) {
            ic_delete_error = ContextCompat.getDrawable(getContext(), R.mipmap.icon_login_edit_error);
            if (ic_delete_error != null) {
                ic_delete_error.setBounds(delete_x, delete_y, delete_width, delete_height);
                setCompoundDrawables(null, null, ic_delete_error, null);
            }
            if (lineView != null) {
                lineView.setBackgroundColor(ContextCompat.getColor(lineView.getContext(), R.color.color_FF445A));
            }
        }
    }

    public void setError(boolean error) {
        this.error = error;
    }


    public void setLineViewColor(int checkColor) {
        lineView.setBackgroundColor(ContextCompat.getColor(lineView.getContext(), checkColor));
    }

    public interface DeleteEditTextFocusListener {
        void onFocusChanged(boolean focused);
    }

    public interface DeleteEditTextChangedListener {
        void onTextChanged(CharSequence text);
    }

}